#!/bin/bash
. $TONE_ROOT/lib/common.sh
. $TONE_ROOT/lib/testinfo.sh

run() {
    # 日志
    log_success() {
    echo "$(date +'%Y-%m-%d %H:%M:%S') $1"
    
    }

    ip_address=$(ifconfig | grep 'inet ' | awk '{print $2}' | grep -v '127.0.0.1' | head -n 1)

   # 检查是否成功获取到 IP 地址
    if [ -n "$ip_address" ]; then
        echo "当前系统的 IP 地址是: $ip_address" 
    else
        echo "无法获取系统的 IP 地址"
    fi
    run_cpu_test() {
        local params=""
       
        [ -n "$num" ] && params="$params --mutex-num $num"
        [ -n "$locks" ] && params="$params --mutex-locks $locks"
        [ -n "$loops" ] && params="$params --mutex-loops $loops"
        [ -n "$driver" ] && params="$params --db-driver $driver"
        [ -n "$host" ] && params="$params --mysql-host    $host"
        [ -n "$db" ] && params="$params --mysql-db    $db"
        [ -n "$user" ] && params="$params --mysql-user    $user"
        [ -n "$size" ] && params="$params --tables-size    $size"
        [ -n "$interval" ] && params="$params --report-interval    $interval"
        [ -n "$password" ] && params="$params --mysql-password    $password"
        [ -n "$port" ] && params="$params --mysql-port    $port"
        [ -n "$tables" ] && params="$params --tables    $tables"
        [ -n "$time" ] && params="$params --time    $time"
        # 执行 sysbench 测试CPU素数计算性能命令并记录日志
        logger $TONE_BM_RUN_DIR/bin/sysbench $testname --cpu-max-prime=$prime --threads=${nr_task:-1}  $run
    }

    run_mutex_test() {
        local params=""
       
        [ -n "$prime" ] && params="$params --cpu_max_prime $prime"
        [ -n "$driver" ] && params="$params --db-driver $driver"
        [ -n "$host" ] && params="$params --mysql-host    $host"
        [ -n "$db" ] && params="$params --mysql-db    $db"
        [ -n "$user" ] && params="$params --mysql-user    $user"
        [ -n "$size" ] && params="$params --tables-size    $size"
        [ -n "$interval" ] && params="$params --report-interval    $interval"
        [ -n "$password" ] && params="$params --mysql-password    $password"
        [ -n "$port" ] && params="$params --mysql-port    $port"
        [ -n "$tables" ] && params="$params --tables    $tables"
        [ -n "$time" ] && params="$params --time    $time"
        # 执行 sysbench测试Mutex互斥锁性能命令并记录日志
        logger $TONE_BM_RUN_DIR/bin/sysbench --test=$testname --mutex-num=$num  --mutex-locks=$locks --mutex-loops=$loops --num-threads=${nr_task:-1}  $run
    }

run_mysql() {
    # 重新启动 MySQL 服务
    systemctl restart mysqld.service

    # 停止 MySQL 服务
    systemctl stop mysqld.service

    # 删除 MySQL 数据目录中的所有文件
    sudo rm -rf /var/lib/mysql/*

    # 清空 MySQL 日志文件
    sudo truncate -s 0 /var/log/mysql/mysqld.log

    # 使用初始化选项重新初始化 MySQL
    sudo mysqld --initialize

    # 查找并提取临时密码
    temp_password=$(sudo grep 'temporary password' /var/log/mysql/mysqld.log | awk '{print $NF}')
    # 打印临时密码
    log_success "Temporary password: $temp_password"

    # 修改 MySQL 目录下的所有者和组
    sudo chown -R mysql:mysql /var/lib/mysql

    # 重启 MySQL 服务
    systemctl restart mysqld.service 

    # 使用临时密码修改 root 用户的密码
    mysql -u root -p"$temp_password" --connect-expired-password -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '$password';"
    if [ $? -eq 0 ]; then
        log_success "MySQL root password updated."
    else
        log_success "Error: Failed to update MySQL root password."
    fi

    # 创建数据库
    mysql -u root -p$password -e "CREATE DATABASE $db;"

    # 创建用户并授予权限
    mysql -u root -p$password -e "CREATE USER '$user'@'%' IDENTIFIED BY '$password';"
    mysql -u root -p$password -e "GRANT ALL PRIVILEGES ON $db.* TO '$user'@'%';"

    # 刷新权限
    mysql -u root -p$password -e "FLUSH PRIVILEGES;"

    log_success "MySQL configuration and user setup completed successfully."
}


    prepare_oltp_mysql_test() {
        local params=""
        # 如果参数非空，则添加到 params 变量中
       
        [ -n "$prime" ] && params="$params --cpu_max_prime $prime"
        [ -n "$num" ] && params="$params --mutex-num $num"
        [ -n "$locks" ] && params="$params --mutex-locks $locks"
        [ -n "$loops" ] && params="$params --mutex-loops $loops" 
        # 执行sysbench 准备mysql测试数据命令并记录日志
        logger $TONE_BM_RUN_DIR/bin/sysbench   $testname  --db-driver=$driver   --mysql-db=$db   --mysql-user=$user   --threads=$nr_task --table-size=$size   --report-interval=$interval  --mysql-host=$ip_address   --mysql-password=$password    --mysql-port=$port    --tables=$tables --time=$time  $run
    }

 run_oltp_mysql_test() {
        local params=""
        # 如果参数非空，则添加到 params 变量中
       
        [ -n "$prime" ] && params="$params --cpu_max_prime $prime"
        [ -n "$num" ] && params="$params --mutex-num $num"
        [ -n "$locks" ] && params="$params --mutex-locks $locks"
        [ -n "$loops" ] && params="$params --mutex-loops $loops" 
        logger $TONE_BM_RUN_DIR/bin/sysbench   $testname  --db-driver=$driver   --mysql-db=$db   --mysql-user=$user   --threads=$nr_task --table-size=$size   --report-interval=$interval  --mysql-host=$ip_address   --mysql-password=$password     --mysql-port=$port  --tables=$tables --time=$time  $run
    }

# pgsql准备
    run_pgsql() {
# 使用初始化选项重新初始化 PostgreSQL
sudo postgresql-setup initdb
log_success "PostgreSQL 数据库初始化成功."

# 重启启动 PostgreSQL 服务
sudo systemctl restart postgresql
log_success "重启动 PostgreSQL 服务成功."

# 设置密码
sudo -i -u postgres psql -c "ALTER USER postgres PASSWORD '$password';"
log_success "设置 PostgreSQL 密码成功."

# 创建数据库
sudo  -i -u postgres psql -c "CREATE DATABASE $db;"
log_success "创建数据库成功."

# 创建用户并授予权限
sudo  -i -u postgres psql -c "CREATE USER $user WITH ENCRYPTED PASSWORD '$password';"
sudo  -i -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE $db TO $user;"
log_success "创建用户并授予权限成功."

# 要添加的规则
RULE="host         all             all          0.0.0.0/0    md5"

# PostgreSQL 数据目录路径
PG_DATA_DIR="/var/lib/pgsql/data"

# pg_hba.conf 文件路径
PG_HBA_CONF="$PG_DATA_DIR/pg_hba.conf"

# 检查 pg_hba.conf 文件是否存在
if [ ! -f "$PG_HBA_CONF" ]; then
    echo "Error: pg_hba.conf file not found at $PG_HBA_CONF"
    exit 1
fi

# 检查规则是否已经存在
if grep -q "$RULE" "$PG_HBA_CONF"; then
    echo "规则 $RULE 已经存在于 $PG_HBA_CONF 文件中，不进行修改。"
else
    # 将规则添加到 pg_hba.conf 文件
    echo "$RULE" | sudo tee -a "$PG_HBA_CONF" > /dev/null
    echo "成功添加规则到 $PG_HBA_CONF 文件。"
fi

# 设置变量
CONF_FILE="/var/lib/pgsql/data/postgresql.conf"
LISTEN_ADDRESSES="'*'"
PORT="5432"

# 检查是否已经修改过 listen_addresses 和 port
if grep -q "^listen_addresses" "$CONF_FILE" && grep -q "^port" "$CONF_FILE"; then
    echo "listen_addresses 和 port 已经修改过，跳过执行。"
else
    
    # 设置 listen_addresses 和 port 的值
    sed -i "s/#listen_addresses = 'localhost'/listen_addresses = ${LISTEN_ADDRESSES}/" "$CONF_FILE"
    sed -i "s/#port = 5432/port = ${PORT}/" "$CONF_FILE" 

    # 修改 postgresql.conf 文件
    sed -i "/^#listen_addresses/s/^#//" "$CONF_FILE"
    sed -i "/^#port/s/^#//" "$CONF_FILE"

  

    echo "成功修改 postgresql.conf 文件。"
fi


   }


   prepare_oltp_pgsql_test() {
        local params=""
        # 如果参数非空，则添加到 params 变量中
       
        [ -n "$prime" ] && params="$params --cpu_max_prime $prime"
        [ -n "$num" ] && params="$params --mutex-num $num"
        [ -n "$locks" ] && params="$params --mutex-locks $locks"
        [ -n "$loops" ] && params="$params --mutex-loops $loops" 
        # 执行sysbench 准备mysql测试数据命令并记录日志
        logger $TONE_BM_RUN_DIR/bin/sysbench   $testname  --db-driver=$driver   --pgsql-db=$db   --pgsql-user=$user   --threads=$nr_task --table-size=$size   --report-interval=$interval  --pgsql-host=$ip_address   --pgsql-password=$password    --pgsql-port=$port    --tables=$tables --time=$time  $run
    }

 run_oltp_pgsql_test() {
        local params=""
        # 如果参数非空，则添加到 params 变量中
       
        [ -n "$prime" ] && params="$params --cpu_max_prime $prime"
        [ -n "$num" ] && params="$params --mutex-num $num"
        [ -n "$locks" ] && params="$params --mutex-locks $locks"
        [ -n "$loops" ] && params="$params --mutex-loops $loops" 
        logger $TONE_BM_RUN_DIR/bin/sysbench   $testname  --db-driver=$driver   --pgsql-db=$db   --pgsql-user=$user   --threads=$nr_task --table-size=$size   --report-interval=$interval  --pgsql-host=$ip_address   --pgsql-password=$password     --pgsql-port=$port  --tables=$tables --time=$time  $run
    }

    # 检查测试类型并执行相应的函数
    if [ "$testname" = "cpu" ]; then
        run_cpu_test
       
    elif [ "$testname" = "mutex" ]; then
        run_mutex_test
        
    elif [ "$testname" = "oltp_insert" ]  && [ "$run" = "prepare" ] && [ "$driver" = "mysql" ] ; then
        run_mysql
        prepare_oltp_mysql_test
    elif [ "$driver" = "mysql" ]  && [ "$run" = "run" ]; then
        run_oltp_mysql_test
         
    elif [ "$testname" = "oltp_insert" ]  && [ "$run" = "prepare" ] && [ "$driver" = "pgsql" ] ; then
         run_pgsql
        prepare_oltp_pgsql_test
     elif [ "$driver" = "pgsql" ]  && [ "$run" = "run" ]; then
        run_oltp_pgsql_test
       
    fi

}

parse() {
    $TONE_BM_SUITE_DIR/sysbench.awk
#   chmod a+w $TONE_BM_SUITE_DIR/sysbench_awk.awk
}
